package com.google.screen;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.google.screen.Control.Logout;
import com.google.zxing.client.android.CaptureActivity;
import com.google.zxing.client.android.R;

public class History extends Activity implements OnItemClickListener {

	private ListView mLstHistory;
	private DBAdapter mDB;
	private ArrayList<ContentValues> mALstHistory;
	private ArrayList<String> mALstTitle;
	private String mStrToken;
	private SharedPreferences mSharedPref;
	private RelativeLayout mRlayMenu;
	private ImageView mImgMenu;
	private boolean mBlnMenu = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.history);

		mLstHistory = (ListView) findViewById(R.id.lstHistory);

		mStrToken = getIntent().getExtras().getString("Token");
		mSharedPref = getSharedPreferences("BarcodePref", Context.MODE_PRIVATE);

		mDB = new DBAdapter(this);
		mDB.open();

		loadListHistory();
		mLstHistory.setOnItemClickListener(this);

		mRlayMenu = (RelativeLayout) findViewById(R.id.rlayHistoryMenu);
		mImgMenu = (ImageView) findViewById(R.id.imgHistoryLogo);

		mImgMenu.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (mBlnMenu) {
					mRlayMenu.removeAllViews();
					mRlayMenu.setVisibility(View.GONE);
					mBlnMenu = false;
				} else {
					LayoutInflater inf = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
					View view = inf.inflate(R.layout.menu, null);
					mRlayMenu.addView(view);
					mRlayMenu.setVisibility(View.VISIBLE);
					mBlnMenu = true;
				}
			}
		});
	}

	private void loadListHistory() {
		mALstHistory = mDB.queryAllHistory();
		mALstTitle = new ArrayList<String>();
		;
		ContentValues content;
		for (int i = 0; i < mALstHistory.size(); i++) {
			content = mALstHistory.get(i);
			mALstTitle.add(content.getAsString("title"));
		}
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				R.layout.mytextview, mALstTitle);
		mLstHistory.setAdapter(adapter);
		mLstHistory.setCacheColorHint(Color.GRAY);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		return true;
	}

	private void showInformations(ContentValues content) {
		Intent intent = new Intent(History.this, com.google.screen.Result.class);
		intent.putExtra("Token", mStrToken);
		intent.putExtra("barcode", content.getAsString("barcode"));
		intent.putExtra("coupon_id", content.getAsString("coupon_id"));
		intent.putExtra("category_id", content.getAsString("category_id"));
		intent.putExtra("title", content.getAsString("title"));
		intent.putExtra("description", content.getAsString("description"));
		intent.putExtra("image", content.getAsString("image"));
		intent.putExtra("nbr_to_print", content.getAsString("nbr_to_print"));
		intent.putExtra("nbr_printed", content.getAsString("nbr_printed"));
		intent.putExtra("start_date", content.getAsString("start_date"));
		intent.putExtra("end_date", content.getAsString("end_date"));
		intent.putExtra("status", content.getAsString("status"));
		intent.putExtra("checkout", content.getAsString("checkout"));
		startActivity(intent);
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		showInformations(mALstHistory.get(arg2));
	}

	@Override
	public void onBackPressed() {
		Intent intent = new Intent(History.this, Control.class);
		intent.putExtra("Token", mStrToken);
		startActivity(intent);
		finish();
		super.onBackPressed();
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		if (mRlayMenu.isShown()) {
			mRlayMenu.removeAllViews();
			mRlayMenu.setVisibility(View.GONE);
			mBlnMenu = false;
		}
		return super.onTouchEvent(event);
	}

	public void startScan(View v) {
		Intent intent = new Intent(History.this, CaptureActivity.class);
		intent.putExtra("Token", mStrToken);
		startActivity(intent);
		finish();
	}

	public void contact(View v) {
		Intent intent = new Intent(History.this, Contact.class);
		intent.putExtra("Token", mStrToken);
		startActivity(intent);
		finish();
	}

	public void logout(View v) {
		new Logout(this, mStrToken).execute();
	}

	public void parametres(View v) {
		mRlayMenu.removeAllViews();
		mRlayMenu.setVisibility(View.GONE);
	}

	public void viewFAQs(View v) {
		Intent intent = new Intent(History.this, FAQs.class);
		intent.putExtra("Token", mStrToken);
		startActivity(intent);
		finish();
	}

	public void viewControlHistory(View v) {
		mRlayMenu.removeAllViews();
		mRlayMenu.setVisibility(View.GONE);
	}

	public void setStringPref(SharedPreferences sharedPref, String name,
			String value) {
		SharedPreferences.Editor editor = sharedPref.edit();
		editor.putString(name, value);
		editor.commit();
	}

	public class Logout extends AsyncTask<String, Integer, String> {

		private Context mCtx;
		private ProgressDialog mProDialog;
		private String mStrToken;
		private Intent intent;

		public Logout(Context ctx, String strToken) {
			mCtx = ctx;
			mProDialog = new ProgressDialog(mCtx);
			mStrToken = strToken;
			intent = new Intent(mCtx, Login.class);
		}

		@Override
		protected String doInBackground(String... params) {
			setStringPref(mSharedPref, "token", "");
			StringBuffer uri = new StringBuffer(
					"http://www.chimrawa.com/service.php/authentication/logout?");
			uri.append("token=" + URLEncoder.encode(mStrToken));
			Log.i("uri", uri.toString());
			String param[] = new String[2];
			param[0] = uri.toString();
			param[1] = "logout";

			Authentication authentication = new Authentication(mCtx);
			authentication.execute(param);
			try {
				ContentValues data = authentication.get();
				if (data != null) {
					if (data.getAsInteger("code") == 1
							&& data.getAsString("statusheader").equals("ok")) {
						return "logout";
					} else {
						return "disconnect";
					}
				} else {
					return "notconnect";
				}
			} catch (InterruptedException e) {
				Log.i("InterruptedException", e.getMessage());
			} catch (ExecutionException e) {
				Log.i("ExecutionException", e.getMessage());
			}
			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			mProDialog.dismiss();
			if (result.equals("logout")) {
				startActivity(intent);
				finish();
			}
			if (result.equals("disconnect")) {
				Toast.makeText(mCtx, "Can't disconnect!", Toast.LENGTH_SHORT)
						.show();
			}
			if (result.equals("notconnect")) {
				Toast.makeText(mCtx, "Can't connect to server!",
						Toast.LENGTH_SHORT).show();
			}
			super.onPostExecute(result);
		}

		@Override
		protected void onPreExecute() {
			mProDialog.setTitle("Logout Account");
			mProDialog.setMessage("Connecting...");
			mProDialog.setCancelable(false);
			mProDialog.setCanceledOnTouchOutside(false);
			mProDialog.show();
			super.onPreExecute();
		}

	}

}
